package com.mycat.manager.controller.auth;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.mycat.auth.domain.AuthResource;
import com.mycat.auth.dto.auth.ResourcesTreeDTO;
import com.mycat.auth.dto.common.CommonDTO;
import com.mycat.auth.service.AuthResourceService;
import com.mycat.common.entity.InvokeResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 后台权限模块之资源管理页面
 *
 * @author Roger
 */
@Controller
@RequestMapping("/resource")
public class ResourceController {
    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    @Autowired
    private AuthResourceService authResourceService;

    /**
     * 进入资源管理页面
     */
    @RequestMapping(method = RequestMethod.GET)
    @RequiresPermissions("resource:view")
    public String toList() {
        return "auth/resource";
    }

    /**
     * 初始化菜单树
     * @param parentId 父节点
     */
    @RequestMapping(value = "/initResourceTree",method = RequestMethod.GET)
    @RequiresPermissions("resource:view")
    @ResponseBody
    public ResponseEntity<InvokeResult<List<ResourcesTreeDTO>>> initResourceTree(@RequestParam(value = "parentId",required = true) Integer parentId) {
        InvokeResult invokeResult = null;
        try {
            List<ResourcesTreeDTO> resources = authResourceService.findResourceTree(parentId);
            if(null != resources && resources.size()>0){
                invokeResult = InvokeResult.success(resources);
            }else{
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取分页数据
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     */
    @RequestMapping(value = "/{pageNum}/{pageSize}", method = RequestMethod.GET)
    @RequiresPermissions("resource:view")
    @ResponseBody
    public ResponseEntity<InvokeResult<PageInfo<AuthResource>>> page(@PathVariable int pageNum,
                                                                     @PathVariable int pageSize,
                                                                     @RequestParam(value = "parentId", required = true) Integer parentId) {
        InvokeResult invokeResult = null;
        try {
            Page<AuthResource> page = new Page<AuthResource>() {{
                this.setPageNum(pageNum);
                this.setPageSize(pageSize);
            }};
            AuthResource resource = new AuthResource() {{
                this.setParentId(parentId);
            }};
            PageInfo<AuthResource> pageInfo = authResourceService.findResources(page, resource);
            if (null != pageInfo && null != pageInfo.getList() && pageInfo.getList().size() > 0) {
                invokeResult = InvokeResult.success(pageInfo);
            } else {
                invokeResult = InvokeResult.pass_no_data();
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<>(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 获取单个对象
     *
     * @param id Id
     */
    @RequiresPermissions("resource:view")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InvokeResult> getAdmin(@PathVariable Integer id) {
        InvokeResult invokeResult = null;
        try {
            if (null != id) {
                AuthResource resource = new AuthResource() {{
                    super.setId(id);
                }};
                AuthResource authResource = authResourceService.findResource(resource);
                invokeResult = InvokeResult.success(authResource);
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 删除对象
     *
     * @param commonDTO 删除数据DTO
     */
    @RequiresPermissions("resource:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<InvokeResult> delete(@RequestBody CommonDTO commonDTO) {
        InvokeResult invokeResult = null;
        try {
            if (null != commonDTO && null != commonDTO.getIds() && commonDTO.getIds().length > 0) {
                authResourceService.delResource(commonDTO.getIds());
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 新增数据
     *
     * @param authResource 新增对象
     */
    @RequiresPermissions("resource:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> add(AuthResource authResource) {
        InvokeResult invokeResult = null;
        try {
            if (null != authResource) {
                authResourceService.addResource(authResource);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }

    /**
     * 修改数据
     *
     * @param authResource 修改对象
     */
    @RequiresPermissions("resource:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<InvokeResult> edit(AuthResource authResource) {
        InvokeResult invokeResult = null;
        try {
            if (null != authResource && null != authResource.getId()) {
                authResourceService.updateResource(authResource);
                invokeResult = InvokeResult.success();
            } else {
                invokeResult = InvokeResult.failure("参数错误！");
            }
        } catch (Exception e) {
            invokeResult = InvokeResult.error();
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity(invokeResult, HttpStatus.valueOf(invokeResult.getCode()));
    }
}
